<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
<meta name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">

    <meta name="author" content="ZhangPing">





<title>kotlin基础(一) | ZhangPing&#39;s Blog</title>



    <link rel="icon" href="/favicon.ico">




    <!-- stylesheets list from _config.yml -->
    
    <link rel="stylesheet" href="/css/style.css">
    



    <!-- scripts list from _config.yml -->
    
    <script src="/js/script.js"></script>
    
    <script src="/js/tocbot.min.js"></script>
    



    
    
        
    


<meta name="generator" content="Hexo 4.2.0"></head>
<body>
    <div class="wrapper">
        <header>
    <nav class="navbar">
        <div class="container">
            <div class="navbar-header header-logo"><a href="/">ZhangPing&#39;s Blog</a></div>
            <div class="menu navbar-right">
                
                    <a class="menu-item" href="/archives">Posts</a>
                
                    <a class="menu-item" href="/category">Categories</a>
                
                    <a class="menu-item" href="/tag">Tags</a>
                
                    <a class="menu-item" href="/about">About</a>
                
                <input id="switch_default" type="checkbox" class="switch_default">
                <label for="switch_default" class="toggleBtn"></label>
            </div>
        </div>
    </nav>

    
    <nav class="navbar-mobile" id="nav-mobile">
        <div class="container">
            <div class="navbar-header">
                <div>
                    <a href="/">ZhangPing&#39;s Blog</a><a id="mobile-toggle-theme">·&nbsp;Light</a>
                </div>
                <div class="menu-toggle" onclick="mobileBtn()">&#9776; Menu</div>
            </div>
            <div class="menu" id="mobile-menu">
                
                    <a class="menu-item" href="/archives">Posts</a>
                
                    <a class="menu-item" href="/category">Categories</a>
                
                    <a class="menu-item" href="/tag">Tags</a>
                
                    <a class="menu-item" href="/about">About</a>
                
            </div>
        </div>
    </nav>

</header>
<script>
    var mobileBtn = function f() {
        var toggleMenu = document.getElementsByClassName("menu-toggle")[0];
        var mobileMenu = document.getElementById("mobile-menu");
        if(toggleMenu.classList.contains("active")){
           toggleMenu.classList.remove("active")
            mobileMenu.classList.remove("active")
        }else{
            toggleMenu.classList.add("active")
            mobileMenu.classList.add("active")
        }
    }
</script>
        <div class="main">
            <div class="container">
    
    
        <div class="post-toc">
    <div class="tocbot-list">
    </div>
    <div class="tocbot-list-menu">
        <a class="tocbot-toc-expand" onclick="expand_toc()">Expand all</a>
        <a onclick="go_top()">Back to top</a>
        <a onclick="go_bottom()">Go to bottom</a>
    </div>
</div>

<script>
    document.ready(
        function () {
            tocbot.init({
                tocSelector: '.tocbot-list',
                contentSelector: '.post-content',
                headingSelector: 'h1, h2, h3, h4, h5',
                collapseDepth: 1,
                orderedList: false,
                scrollSmooth: true,
            })
        }
    )

    function expand_toc() {
        var b = document.querySelector(".tocbot-toc-expand");
        tocbot.init({
            tocSelector: '.tocbot-list',
            contentSelector: '.post-content',
            headingSelector: 'h1, h2, h3, h4, h5',
            collapseDepth: 6,
            orderedList: false,
            scrollSmooth: true,
        });
        b.setAttribute("onclick", "collapse_toc()");
        b.innerHTML = "Collapse all"
    }

    function collapse_toc() {
        var b = document.querySelector(".tocbot-toc-expand");
        tocbot.init({
            tocSelector: '.tocbot-list',
            contentSelector: '.post-content',
            headingSelector: 'h1, h2, h3, h4, h5',
            collapseDepth: 1,
            orderedList: false,
            scrollSmooth: true,
        });
        b.setAttribute("onclick", "expand_toc()");
        b.innerHTML = "Expand all"
    }

    function go_top() {
        window.scrollTo(0, 0);
    }

    function go_bottom() {
        window.scrollTo(0, document.body.scrollHeight);
    }

</script>
    

    
    <article class="post-wrap">
        <header class="post-header">
            <h1 class="post-title">kotlin基础(一)</h1>
            
                <div class="post-meta">
                    
                        Author: <a itemprop="author" rel="author" href="/">ZhangPing</a>
                    

                    
                        <span class="post-time">
                        Date: <a href="#">February 17, 2021&nbsp;&nbsp;0:00:00</a>
                        </span>
                    
                    
                        <span class="post-category">
                    Category:
                            
                                <a href="/categories/%E7%AC%94%E8%AE%B0/">笔记</a>
                            
                        </span>
                    
                </div>
            
        </header>

        <div class="post-content">
            <h2 id="函数声明"><a href="#函数声明" class="headerlink" title="函数声明"></a>函数声明</h2><p>声明函数要⽤⽤** fun **关键字，就像声明类要⽤ class 关键字⼀样</p>
<ul>
<li>「函数参数」的「参数类型」是在「参数名」的右边</li>
<li>函数的「返回值」在「函数参数」右边使⽤ : 分隔，没有返回值时可以省略</li>
<li>声明没有返回值的函数：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fun main( ) &#123;</span><br><span class="line">&#x2F;&#x2F; ..</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>声明有返回值的参数:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fun sum(x: Int, y: Int): Int &#123;</span><br><span class="line">	return x + y</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="变量声明"><a href="#变量声明" class="headerlink" title="变量声明"></a>变量声明</h2><ul>
<li>声明变量需要通过关键字， var 声明可读可写变量， val 声明只读变量</li>
<li>「类型」在「变量量名」的右边，⽤ : 分割，同时如果满⾜「类型推断」，类</li>
<li>型可以省略</li>
<li>创建对象直接调⽤构造器，不需要 new 关键字</li>
</ul>
<p>声明可读可写变量：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var age: Int &#x3D; 18</span><br></pre></td></tr></table></figure>

<p>声明只读变量:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">val name: String &#x3D; &quot;Hello, Kotlin!&quot;</span><br></pre></td></tr></table></figure>

<p>声明对象：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">val user: User &#x3D; User()</span><br></pre></td></tr></table></figure>

<h2 id="类型推断"><a href="#类型推断" class="headerlink" title="类型推断"></a>类型推断</h2><p>在变量声明的基础上，如果表达式右边的类型是可以推断出来，那么类型可以省略:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var age &#x3D; 18</span><br><span class="line">val name &#x3D; &quot;Hello, Kotlin!&quot;</span><br><span class="line">val user &#x3D; User()</span><br></pre></td></tr></table></figure>

<h2 id="继承类-实现接⼝"><a href="#继承类-实现接⼝" class="headerlink" title="继承类/实现接⼝"></a>继承类/实现接⼝</h2><p>继承类和实现接⼝都是⽤的<strong>:</strong>，如果类中没有构造器 ( <strong>constructor</strong> )，需要在⽗类类名后⾯加上 <strong>()</strong> ：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">class MainActivity : BaseActivity(),</span><br><span class="line">View.OnClickListener</span><br></pre></td></tr></table></figure>

<h2 id="空安全设计"><a href="#空安全设计" class="headerlink" title="空安全设计"></a>空安全设计</h2><p>Kotlin 中的类型分为「可空类型」和「不可空类型」：</p>
<ul>
<li>不可空类型</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">val edit Text : Edit Text</span><br></pre></td></tr></table></figure>

<ul>
<li>可空类型</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">val edit Text : Edit Text ?</span><br></pre></td></tr></table></figure>

<h2 id="调⽤符"><a href="#调⽤符" class="headerlink" title="调⽤符"></a>调⽤符</h2><ul>
<li>!! 强⾏调⽤符</li>
<li>?. 安全调⽤符</li>
</ul>
<h2 id="lateinit-关键字"><a href="#lateinit-关键字" class="headerlink" title="lateinit 关键字"></a>lateinit 关键字</h2><ul>
<li>lateinit 只能修饰 var 可读可写变量(思考下为什么)</li>
<li>lateinit 关键字声明的变量的类型必须是「不可空类型」</li>
<li>lateinit 声明的变量不能有「初始值」</li>
<li>lateinit 声明的变量不能是「基本数据类型」</li>
<li>在构造器中初始化的属性不需要 lateinit 关键字</li>
</ul>
<h2 id="平台类型"><a href="#平台类型" class="headerlink" title="平台类型"></a>平台类型</h2><p>在类型后⾯⾯加上⼀个感叹号的类型是「平台类型」Java 中可以通过注解减少这种平台类型的产</p>
<ul>
<li>@Nullable 表示可空类型</li>
<li>@NotNull @NonNull 表示不可空类型</li>
</ul>
<h2 id="类型判断"><a href="#类型判断" class="headerlink" title="类型判断"></a>类型判断</h2><ul>
<li><strong>is</strong> 判断属于某类型</li>
<li><strong>!is</strong> 判断不属于某类型</li>
<li><strong>as</strong> 类型强转，失败时抛出类型强转失败异常</li>
<li><strong>as?</strong> 类型强转，但失败时不会抛出异常⽽是返回 null</li>
</ul>
<h2 id="获取-Class-对象"><a href="#获取-Class-对象" class="headerlink" title="获取 Class 对象"></a>获取 Class 对象</h2><p>使⽤ <strong>类名::class</strong> 获取的是 Kotlin 的类型是 KClass<br>使⽤ <strong>类名::class.java</strong> 获取的是 Java 的类型</p>
<h2 id="setter-getter"><a href="#setter-getter" class="headerlink" title="setter/getter"></a>setter/getter</h2><p>在 Kotlin 声明属性的时候(没有使⽤ private 修饰)，会⾃动⽣成⼀个私有属性和⼀对公开的 setter/getter 函数。</p>
<p>在写 setter/getter 的时候使⽤ field 来代替内部的私有属性(防⽌递归栈溢出)。</p>
<p>为什么 EditText.getText() 的时候可以简化，但是EditText.setText() 的时候不能和 TextView.setText() ⼀样简化?因为 EditText.getText() 获得的类型是 Editable ，对应的如果EditText.setText() 传⼊的参数也是 Editable 就可以简化了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">val newEditable &#x3D; Editable.Factory.getInstance().newEditable(&quot;Kotlin&quot;)</span><br><span class="line">et_username.text &#x3D; newEditable</span><br></pre></td></tr></table></figure>

<h2 id="构造器"><a href="#构造器" class="headerlink" title="构造器"></a>构造器</h2><p>使⽤ <strong>constructor</strong> 关键字声明构造器</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">class User &#123;</span><br><span class="line">	constructor()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果我们在构造器主动调⽤了了⽗类构造，那么在继承类的时候就不能在类的后⾯加上⼩括号</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">constructor(context: Context) : this(context, null)</span><br><span class="line">&#x2F;&#x2F; 主动调⽤⽤了⽗类的构造器</span><br><span class="line">constructor(context: Context, attr: AttributeSet?) :</span><br><span class="line">super(context, attr)</span><br></pre></td></tr></table></figure>

<h2 id="JvmField-⽣成属性"><a href="#JvmField-⽣成属性" class="headerlink" title="@JvmField ⽣成属性"></a>@JvmField ⽣成属性</h2><p>通过 <strong>@JvmField</strong> 注解可以让编译器只⽣成⼀个 <strong>public</strong> 的成员属性，不⽣成对应的 <strong>setter/getter</strong> 函数</p>
<h2 id="Any-和-Unit"><a href="#Any-和-Unit" class="headerlink" title="Any 和 Unit"></a>Any 和 Unit</h2><ul>
<li><strong>Any</strong> Kotlin 的顶层⽗类是 <strong>Any</strong> ，对应 Java 当中的 <strong>Object</strong> ，但是⽐ <strong>Object</strong> 少了 <strong>wait()/notify()</strong> 等函数</li>
<li>Unit Kotlin 中的 Unit 对应 Java 中的 void</li>
</ul>
<h2 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h2><p>使⽤ <strong>arrayof()</strong> 来创建数组，基本数据类型使⽤对应的 <strong>intArrayOf()</strong> 等</p>
<h2 id="静态函数和属性"><a href="#静态函数和属性" class="headerlink" title="静态函数和属性"></a>静态函数和属性</h2><ul>
<li>顶层函数</li>
<li>object</li>
<li>companion object</li>
</ul>
<p>其中，「顶层函数」直接在⽂件中定义函数和属性，会直接⽣成静态的，在 Java 中通过「⽂件名Kt」来 访问，同时可以通过 <strong>@file:JvmName</strong> 注解来修改这个「类名」。</p>
<p><em>需要注意，这种顶层函数不要声明在 <strong>module</strong> 内最顶层的包中，⾄少要在⼀个包中例如 <strong>com</strong> 。不然不能⽅便使⽤。</em></p>
<p><strong>object</strong> 和 <strong>companion object</strong> 都是⽣成单例例对象，然后通过单例对象访问函数和属性的。</p>
<h2 id="JvmStatic"><a href="#JvmStatic" class="headerlink" title="@JvmStatic"></a>@JvmStatic</h2><p>通过这个注解将 <strong>object</strong> 和 <strong>companion object</strong> 的内部函数和属性，真正⽣成为静态的。</p>
<h2 id="单例模式-匿名内部类"><a href="#单例模式-匿名内部类" class="headerlink" title="单例模式/匿名内部类"></a>单例模式/匿名内部类</h2><p>通过 <strong>object</strong> 关键字实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 单例</span><br><span class="line">object Singleton &#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 匿名内部类</span><br><span class="line">object : OnClickListener &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="字符串模版"><a href="#字符串模版" class="headerlink" title="字符串模版"></a>字符串模版</h2><p>通过 ${} 的形式来作为字符串模版字符串模版</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">val number &#x3D; 100</span><br><span class="line">val text &#x3D; &quot;向你转账$&#123;number&#125;元。 &quot;</span><br><span class="line">&#x2F;&#x2F; 如果只是单⼀的变量，可以省略掉 &#123;&#125;</span><br><span class="line">val text2 &#x3D; &quot;向你转账$number元。 &quot;</span><br></pre></td></tr></table></figure>

<h2 id="多⾏字符串"><a href="#多⾏字符串" class="headerlink" title="多⾏字符串"></a>多⾏字符串</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">val s &#x3D; &quot;&quot;&quot;</span><br><span class="line">我是第⼀⾏</span><br><span class="line">我是第⼆⾏</span><br><span class="line">我是第三⾏</span><br><span class="line">&quot;&quot;&quot;.trimIndent()</span><br></pre></td></tr></table></figure>

<h2 id="区间"><a href="#区间" class="headerlink" title="区间"></a>区间</h2><p><strong>200..299</strong> 表示 <strong>200 -&gt; 299</strong> 的区间(包括 <strong>299</strong> )</p>
<h2 id="when-关键字"><a href="#when-关键字" class="headerlink" title="when 关键字"></a>when 关键字</h2><p>Java 当中的 <strong>switch</strong> 的⾼级版，分⽀条件上可以⽀持表达式</p>
<h2 id="受检异常"><a href="#受检异常" class="headerlink" title="受检异常"></a>受检异常</h2><p>Kotlin 不需要使⽤ try-catch 强制捕获异常</p>
<h2 id="声明接⼝-抽象类-枚举-注解"><a href="#声明接⼝-抽象类-枚举-注解" class="headerlink" title="声明接⼝/抽象类/枚举/注解"></a>声明接⼝/抽象类/枚举/注解</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 声明抽象类</span><br><span class="line">abstract class</span><br><span class="line">&#x2F;&#x2F; 声明接⼝</span><br><span class="line">interface</span><br><span class="line">&#x2F;&#x2F; 声明注解</span><br><span class="line">annotation class</span><br><span class="line">&#x2F;&#x2F; 声明枚举</span><br><span class="line">enmu class</span><br></pre></td></tr></table></figure>

<h2 id="编译期常量"><a href="#编译期常量" class="headerlink" title="编译期常量"></a>编译期常量</h2><p>在静态变量上加上 const 关键字变成编译期常量</p>
<h2 id="标签"><a href="#标签" class="headerlink" title="标签"></a>标签</h2><p>在 Java 中通过 「 <strong>类名.this</strong> 例如 <strong>Outer.this</strong> 」 获取⽬标类引⽤<br>在 Kotlin 中通过「 <strong>this@类名</strong> 例如 <strong>this@Outer</strong> 」获取⽬标类引⽤</p>
<h2 id="遍历"><a href="#遍历" class="headerlink" title="遍历"></a>遍历</h2><p>记得让 IDE 来帮助⽣成 for 循环</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">for(item in items)</span><br></pre></td></tr></table></figure>

<h2 id="内部类"><a href="#内部类" class="headerlink" title="内部类"></a>内部类</h2><p>在 Kotlin 当中，内部类默认是静态内部类</p>
<p>通过 <strong>inner</strong> 关键字声明为嵌套内部类</p>
<h2 id="可⻅性修饰符"><a href="#可⻅性修饰符" class="headerlink" title="可⻅性修饰符"></a>可⻅性修饰符</h2><p>默认的可⻅性修饰符是 <strong>public</strong><br>新增的可⻅性修饰符 <strong>internal</strong> 表示当前模块可⻅</p>
<h2 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h2><p>注释中可以在任意地⽅使⽤ <strong>[]</strong> 来引⽤⽬标，代替 Java 中的 <strong>@param @link</strong>等。</p>
<h2 id="⾮空断⾔"><a href="#⾮空断⾔" class="headerlink" title="⾮空断⾔"></a>⾮空断⾔</h2><p>可空类型强制类型转换成不可空类型可以通过在变量后⾯加上 <strong>!!</strong> ，来达到类型转换。</p>
<h2 id="open-final"><a href="#open-final" class="headerlink" title="open/final"></a>open/final</h2><p>Kotlin 中的类和函数，默认是被 <strong>final</strong> 修饰的 ( <strong>abstract</strong> 和 <strong>override</strong> 例外)</p>

        </div>

        
            <section class="post-copyright">
                
                    <p class="copyright-item">
                        <span>Author:</span>
                        <span>ZhangPing</span>
                    </p>
                
                
                    <p class="copyright-item">
                        <span>Permalink:</span>
                        <span><a href="https://zhangpingv5.gitee.io/2021/02/17/kotlin%E5%9F%BA%E7%A1%80(%E4%B8%80)/">https://zhangpingv5.gitee.io/2021/02/17/kotlin%E5%9F%BA%E7%A1%80(%E4%B8%80)/</a></span>
                    </p>
                
                
                    <p class="copyright-item">
                        <span>License:</span>
                        <span>转载请注明出处</span>
                    </p>
                
                
                     <p class="copyright-item">
                         <span>Slogan:</span>
                         <span>Self-descipline grants me freedom.</span>
                     </p>
                

            </section>
        
        <section class="post-tags">
            <div>
                <span>Tag(s):</span>
                <span class="tag">
                    
                    
                        <a href="/tags/%E7%AC%94%E8%AE%B0/"># 笔记</a>
                    
                        
                </span>
            </div>
            <div>
                <a href="javascript:window.history.back();">back</a>
                <span>· </span>
                <a href="/">home</a>
            </div>
        </section>
        <section class="post-nav">
            
                <a class="prev" rel="prev" href="/2021/02/19/kotlin%E5%9F%BA%E7%A1%80(%E4%BA%8C)%20/">kotlin基础(二)</a>
            
            
            <a class="next" rel="next" href="/2021/01/15/%E7%99%BB%E5%BD%95%E5%92%8C%E7%AC%AC%E4%B8%89%E2%BD%85%E6%8E%88%E6%9D%83/">登录和第三⽅授权</a>
            
        </section>


    </article>
</div>

        </div>
        <footer id="footer" class="footer">
    <div class="copyright">
        <span>© ZhangPing | Powered by <a href="https://hexo.io" target="_blank">Hexo</a> & <a href="https://github.com/Siricee/hexo-theme-Chic" target="_blank">Chic</a></span>
    </div>
</footer>

    </div>
</body>
</html>
